package com.qiaoba.auth.job;

import cn.hutool.core.collection.CollUtil;
import com.qiaoba.auth.constant.OnlineUserConstant;
import com.qiaoba.auth.service.OnlineUserService;
import com.qiaoba.nosql.redis.service.RedisService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Objects;
import java.util.Set;

/**
 * 删除不在线的用户
 *
 * @author ailanyin
 * @date 2023-09-18 20:34:02
 */
@Component
@RequiredArgsConstructor
public class DeleteNotOnlineUserJob {

    private final RedisService redisService;
    private final OnlineUserService onlineUserService;

    /**
     * 10分钟执行一次
     */
    @Scheduled(cron = "0 */10 * * * ?")
    public void start() {
        Set<ZSetOperations.TypedTuple<Object>> set = redisService.zSetScoreAll(OnlineUserConstant.DEVICE_HASH_KEY, true);
        if (CollUtil.isNotEmpty(set)) {
            for (ZSetOperations.TypedTuple<Object> tuple : set) {
                if (Objects.nonNull(tuple)) {
                    String deviceSn = tuple.getValue().toString();
                    long time = new BigDecimal(tuple.getScore().toString()).longValue();
                    // 10 * 60 * 1000 = 10分钟（最后访问时间是10分钟之前的就认为已经离线）
                    if (new Date(time - (10 * 60 * 1000)).before(new Date())) {
                        // 删除在线用户相关信息
                        onlineUserService.deleteOnlineInfo(deviceSn);
                    }
                }
            }
        }

    }
}
